package net.qiqb.core.common;

import cn.hutool.core.util.ReflectUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Optional;

public class BeanObjUtil {

    public static void copyFieldValue(Object source,Object target){
        Field[] sourceFields = source.getClass().getDeclaredFields();
        Field[] targetFields = ReflectUtil.getFields(target.getClass());
        for (Field sourceField : sourceFields) {
            if (Modifier.isFinal(sourceField.getModifiers())) {
                continue;
            }
            final Optional<Field> any = Arrays.stream(targetFields).filter(subField -> subField.getName().equals(sourceField.getName())).findAny();
            if (any.isPresent()) {
                Field subField = any.get();
                sourceField.setAccessible(true);
                subField.setAccessible(true);
                try {
                    subField.set(target, sourceField.get(source));
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
